package com.itheima.mm.wx.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.framework.annotation.HmComponent;
import com.itheima.mm.common.QuestionConst;
import com.itheima.mm.database.MmDaoException;
import com.itheima.mm.database.SqlSessionUtils;
import com.itheima.mm.pojo.Catalog;
import com.itheima.mm.pojo.Question;
import com.itheima.mm.wx.dao.CatalogDao;
import com.itheima.mm.wx.dao.QuestionDao;
import com.itheima.mm.wx.dao.WxMemberDao;
import com.itheima.mm.wx.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：wanghao
 * @date ：Created in 2020/11/4
 * @description ：题目分类业务实现类
 * @version: 1.0
 */
@HmComponent("categoryService")
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    @Override
    public List<Map> findCategoryList(Map<String, Object> mapData) {
        // mapData(categoryKind(1-学科目录，2-企业，3-方向),categoryType-101)
        // 判断当前的categoryKind
        Integer categoryKind = (Integer)mapData.get("categoryKind");
        List<Map> mapList = new ArrayList<>();
        if(categoryKind == QuestionConst.CategoryKind.CATALOG.getId()){
            log.debug("按学科目录，获取数据");
            // 调用获取学科目录Dao
            SqlSession sqlSession = SqlSessionUtils.openSession();
            CatalogDao catalogDao = sqlSession.getMapper(CatalogDao.class);
            // 根据条件获取数据
            mapList = catalogDao.selectCataLogList(mapData);
            sqlSession.close();
        } else if (categoryKind == QuestionConst.CategoryKind.COMPANY.getId()){
            log.debug("按企业目录，获取数据");
        } else if (categoryKind == QuestionConst.CategoryKind.INDUSTRY.getId()){
            log.debug("按行业方向，获取数据");
        }
        return mapList;
    }

    @Override
    public Map<String, Object> findCategoryQuestionList(Map<String, Object> mapData) {
        log.debug("CategoryServiceImpl mapData:{}",mapData);
        Map resultMap = new HashMap();
        // 获取分类种类
        Integer categoryKind = (Integer)mapData.get("categoryKind");
        if(categoryKind == QuestionConst.CategoryKind.CATALOG.getId()){
            log.debug("按某一学科目录获取基本信息");
            // 复用分类列表的获取，加入基于分类ID获取某一分类信息
            SqlSession sqlSession = SqlSessionUtils.openSession();
            CatalogDao catalogDao = sqlSession.getMapper(CatalogDao.class);
            // 获取的是分类列表，如果有数据，肯定是要一条数据，基于分类ID（学科目录ID）
            List<Map> mapList = catalogDao.selectCataLogList(mapData);
            if (mapList != null && mapList.size() > 0){
                resultMap = mapList.get(0);
            }
            // 获取某一分类（学科目录）下的题目列表
            QuestionDao questionDao = sqlSession.getMapper(QuestionDao.class);
            List<Question> questionList = questionDao.selectQuestionListByQueryParam(mapData);
            resultMap.put("items",questionList);
            sqlSession.close();
        } else if (categoryKind == QuestionConst.CategoryKind.COMPANY.getId()){
            log.debug("按企业目录，获取数据");
        } else if (categoryKind == QuestionConst.CategoryKind.INDUSTRY.getId()){
            log.debug("按行业方向，获取数据");
        }
        return resultMap;
    }

    @Override
    public void commitQuestion(Map<String, Object> mapData) {
        SqlSession sqlSession = SqlSessionUtils.openSession();
        try {
            // 调用Dao，实现数据保存
            // 获取题目类型，根据类型确定answerTag的值
            Integer type = (Integer)mapData.get("type");
            if (type == QuestionConst.Type.SINGLE.getId() || type == QuestionConst.Type.MULTIPLE.getId()){
                // 单选或多选
                Boolean b1 = (Boolean)mapData.get("answerIsRight");
                if (b1){
                    mapData.put("answerTag",QuestionConst.AnswerTag.PERFECT.ordinal());
                }else {
                    mapData.put("answerTag",QuestionConst.AnswerTag.WRONG.ordinal());
                }
                // 把单选或多选答案，转存JSON串
                String strJSON = JSON.toJSONString(mapData.get("answerResult"));
                mapData.put("answerResult",strJSON);
            }else if (type == QuestionConst.Type.SIMPLE.getId()){
                // 简答题
                Boolean b1 = (Boolean)mapData.get("answerIsRight");
                if (b1){
                    mapData.put("answerTag",QuestionConst.AnswerTag.GOOD.ordinal());
                }else {
                    mapData.put("answerTag",QuestionConst.AnswerTag.BAD.ordinal());
                }
            }
            // 处理收藏标记
            if (mapData.get("isFavorite") != null){
                Boolean b1 = (Boolean)mapData.get("isFavorite");
                // 0 不收藏，1 收藏
                mapData.put("isFavorite",b1?1:0);
            }else {
                // 如果客户没有传isFavorite
                mapData.put("isFavorite",0);
            }
            log.debug("commitQuestion...dao save mapData:{}",mapData);
            // 调用Dao保存数据
            QuestionDao questionDao = sqlSession.getMapper(QuestionDao.class);
            // 先试图更新记录，如果更新失败，再添加记录
            Integer result = questionDao.updateMemberQuestion(mapData);
            if (result == 0){
                questionDao.insertMemberQuestion(mapData);
            }
            // 更新用户最后做题信息
            WxMemberDao wxMemberDao = sqlSession.getMapper(WxMemberDao.class);
            wxMemberDao.updateLastAnswer(mapData);
            sqlSession.commit();
            sqlSession.close();
        }catch (MmDaoException e){
            e.printStackTrace();
            sqlSession.rollback();
            sqlSession.close();
            log.error(e.getMessage());
            throw new MmDaoException(e.getMessage());
        }
    }
}
